/*
 * Licensed to the http://code.google.com/p/crunchutils under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.crunchutils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Provides utility methods that makes use of reflection. Currently this class supports the
 * following:<br>
 * <li> checks whether all the fields of a given object are not empty</li>
 * <li> checks whether the fields with a certain annotation are not empty</li>
 * @author James Selvakumar
 */
public class CrunchClassUtils
{
    private static final Logger logger = LoggerFactory.getLogger(CrunchClassUtils.class);

    /**
     * Checks whether all the fields in the object are not empty
     * @param object
     * @return true if all the fields of the given object are not empty; false otherwise
     */
    public static boolean isFieldsNotEmpty(Object object)
    {
        return isFieldsWithAnnotationNotEmpty(object, null);
    }

    /**
     * Checks whether the fields with the given annotation are not empty
     * @param object
     * @param annotationClass
     * @return true if the respective annotated fields are not empty; false otherwise
     */
    public static boolean isFieldsWithAnnotationNotEmpty(Object object, Class annotationClass)
    {
        Field[] fields = object.getClass().getDeclaredFields();
        logger.debug("No. of fields found in this object: " + fields.length);

        for (Field field : fields) {

            if (annotationClass == null || field.isAnnotationPresent(annotationClass)) {
                if (isFieldNotEmpty(object, field)) {
                    return true;
                }
            }
        }
        logger.debug("All fields are found to be empty!");
        return false;
    }

    protected static boolean isFieldNotEmpty(Object object, Field field)
    {
        try {
            field.setAccessible(true);
            Object fieldValue = field.get(object);

            logger.debug("Field name: " + field.getName() + ", value: " + fieldValue
                    + ", type: " + field.getType());

            if (!field.getName().startsWith("this")) {

                if (isPrimitiveField(field)) {
                    if (isPrimitiveFieldNotEmpty(fieldValue)) {
                        logger.debug("Primitive field is not empty");
                        return true;
                    }
                } else if (fieldValue != null) {
                    logger.debug("The field is not empty");
                    return true;
                }
            }
        } catch (Exception ex) {
            logger.debug("Error occured while checking whether the fields are empty", ex);
        }
        return false;
    }

    /**
     * Checks whether the given field is primitive (int, long, short, byte, double, float, char) or not
     * @param field The field to be checked
     * @return true if the field is a primitive field; false otherwise
     */
    private static boolean isPrimitiveField(Field field)
    {
        String type = field.getType().toString();
        for (String primitiveType : getPrimitiveTypes()) {
            if (type.startsWith(primitiveType)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Checks whether the given primitive field value is not empty.
     * NOTE: This doesn't work for "char" types yet.
     * @param fieldValue
     * @return
     */
    private static boolean isPrimitiveFieldNotEmpty(Object fieldValue)
    {
        String fieldValueAsString = String.valueOf(fieldValue);
        logger.debug("Primitive field value: " + fieldValueAsString);
        if (StringUtils.isNotBlank(fieldValueAsString) && !fieldValueAsString.startsWith("0")) {
            logger.debug("The primitive field is not empty");
            return true;
        }
        logger.debug("The primitive field is empty");
        return false;
    }

    private static List<String> getPrimitiveTypes()
    {
        List<String> primitiveTypes = new ArrayList<String>();
        primitiveTypes.add("char");
        primitiveTypes.add("byte");
        primitiveTypes.add("int");
        primitiveTypes.add("long");
        primitiveTypes.add("float");
        primitiveTypes.add("double");
        return primitiveTypes;
    }
}
